package com.bjh.netty.client;

import com.bjh.netty.codec.RpcDecoder;
import com.bjh.netty.codec.RpcEncoder;
import com.bjh.netty.message.RpcMessage;
import com.bjh.req.Request;
import com.bjh.resp.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RpcClient {

    EventLoopGroup group = new NioEventLoopGroup();

    Bootstrap bootstrap;

    private String ip;

    private Integer port;

    RpcClientHandler rpcClientHandler;

    private ChannelFuture channelFuture;

    public RpcClient(String ip,Integer port) {
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class) // 使用NioSocketChannel作为客户端的通道实现
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //加入处理器
                        rpcClientHandler = new RpcClientHandler();
                        ch.pipeline().addLast(new RpcEncoder(RpcMessage.class));
                        ch.pipeline().addLast(new RpcDecoder(RpcMessage.class));
                        ch.pipeline().addLast(rpcClientHandler);
                    }
                });
//        this.ip = ip;
//        this.port = port;

        try {
            channelFuture = bootstrap.connect(ip, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public Response sendRequest(RpcMessage rpcMessage) throws Exception{
        channelFuture.channel().writeAndFlush(rpcMessage).sync();
        channelFuture.channel().closeFuture().sync();
        log.info("获取返回结果=====================");
        Response response = rpcClientHandler.getResponse();
        return response;
    }
}
